package com.dongdongshop.service.impl;

import com.alibaba.fastjson.JSON;
import com.dongdongshop.data.PageBean;
import com.dongdongshop.mapper.TbGoodsDescMapper;
import com.dongdongshop.mapper.TbGoodsMapper;
import com.dongdongshop.mapper.TbItemMapper;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.pojo.TbItemExample;
import com.dongdongshop.service.GoodsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@DubboService
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private TbGoodsMapper tbGoodsMapper;

    @Autowired
    private TbGoodsDescMapper tbGoodsDescMapper;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void saveGoods(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc, String name, String thp1, String thp2) {
        tbGoodsMapper.saveGoods(tbGoods);
        tbGoodsDesc.setGoodsId(tbGoods.getId());
        tbGoodsDescMapper.insertSelective(tbGoodsDesc);
    }

    @Override
    public PageBean<TbGoods> getGoodsList(Integer pageNumber, Integer pageSize,String goodsName) {
        PageHelper.startPage(pageNumber,pageSize);
        List<TbGoods> list = tbGoodsMapper.getGoodsList(goodsName);
        PageInfo<TbGoods> info = new PageInfo<>(list);
        return new PageBean<TbGoods>(info.getPageNum(), info.getPageSize(), info.getTotal(), info.getPages(), info.getList());
    }

    @Override
    public void setStatu(Long[] id, String status) {

        tbGoodsMapper.setStatu(id,status);
        String ids = new Gson().toJson(id);
        rocketMQTemplate.convertAndSend("my_goods_topic",ids);
    }

    @Override
    public TbGoods findGoods(Long goodsId) {

        return tbGoodsMapper.selectByPrimaryKey(goodsId);
    }

    @Override
    public TbGoodsDesc getGoodsDescById(Long goodsId) {

        return tbGoodsDescMapper.selectByPrimaryKey(goodsId);
    }

    @Override
    public List<TbItem> selectItemListByGoodsId(Long goodsId) {

        TbItemExample example = new TbItemExample();
        TbItemExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        criteria.andStatusEqualTo("1");
        criteria.andStockCountGreaterThan(0);
        return tbItemMapper.selectByExample(example);
    }
}
